package cn.yunhe.control;

import cn.yunhe.util.Path;
import cn.yunhe.entity.User;
import cn.yunhe.server.UserServer;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.jsp.JspFactory;
import javax.servlet.jsp.PageContext;

import com.jspsmart.upload.Request;
import com.jspsmart.upload.SmartUpload;
import com.jspsmart.upload.SmartUploadException;

import java.io.IOException;

@WebServlet("/RegisterServerlet")
public class RegisterServerlet extends HttpServlet {
	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");
		response.setContentType("text/html;charset=UTF-8");
		SmartUpload sm = new SmartUpload();
		PageContext pageContext = JspFactory.getDefaultFactory().getPageContext(this, request, response, null, true,
				8 * 1024, true);  //获取pageContext对象
		String picName = "";
		sm.initialize(pageContext); // 初始化页面对象
		sm.setCharset("UTF-8"); // 设置上传文件的编码
		Request request2 = sm.getRequest();
		try {
			sm.upload(); // 执行上传方法
			sm.save(Path.getPath()); // 保存文件路径
			picName = sm.getFiles().getFile(0).getFileName(); // 获取上传的文件名
		} catch (SmartUploadException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		String username = request2.getParameter("username");
		String password = request2.getParameter("pwd");
		User user = new User(username, password); // 创建用户对象
		user.setPicName(picName);  //设置保存路径
		UserServer userServer = new UserServer();
		boolean flag = userServer.register(user); // 执行注册方法
		if (flag) {
			request.setAttribute("result", "注册成功!!");
			request.getRequestDispatcher("register.jsp").forward(request, response);
		} else {
			request.setAttribute("result", "注册失败,该账号已被占用!!");
			request.getRequestDispatcher("register.jsp").forward(request, response);
		}
	}

	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response); // 调用get方法
	}
}
